package com.ai.zuochengyun.phase01.class01;

/**
 * 大于右侧两倍的数
 */
public class Code08_BiggerThanRightTwice {

    public static void main(String[] args) {
        for (int i = 0; i < 10000; i++) {
            int size = (int)(Math.random() * 10) + 2;
            int[] arr = new int[size];
            for (int j = 0; j < size; j++) {
                arr[j] =  (int)(Math.random() * 50)+1;
                int num1 = test(arr);
                int num2 = calc(arr);
                if (num2 != num1) {
                    System.out.println("oops");
                    return;
                }
            }
        }
        System.out.println("执行完毕");
    }

    private static int calc(int[] arr) {
        if (arr == null || arr.length == 1) {
            return 0;
        }
        return process(arr, 0, arr.length - 1);
    }

    private static int test(int[] arr) {
        if (arr == null || arr.length == 1) {
            return 0;
        }
        int ans = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[i] > arr[j] * 2) {
                    ans++;
                }
            }
        }
        return ans;
    }

    private static int process(int[] arr, int left, int right) {
        if (left == right) {
            return 0;
        }
        int mid = left + ((right - left) >> 1);
        // 统计左侧的
        int leftPart = process(arr, left, mid);
        // 统计右侧的
        int rightPart = process(arr, mid + 1, right);
        // 在合并过程中
        return leftPart + rightPart + merge(arr, left, mid, right);
    }

    private static int merge(int[] arr, int left, int mid, int right) {
        int ans = 0;
        // 左侧区间[left, mid]  右侧区间[mid+1, right]
        // 左侧的数依次和右边的数进行比较
        for (int i = left; i <= mid; i++) {
            // 定义一个区间[mid+1, windowR)  windowR刚开始就在mid+1位置
            int windowR = mid + 1;
            while (windowR <= right && arr[i] > arr[windowR] * 2) {
                windowR++;
            }
            ans += (windowR - (mid + 1));
        }

        int size = right - left + 1;
        int[] help = new int[size];
        int p1 = left;
        int p2 = mid + 1;
        int index = 0;
        while (p1 <= mid && p2 <= right) {
            if (arr[p1] <= arr[p2]) {
                help[index++] = arr[p1++];
            } else {
                help[index++] = arr[p2++];
            }
        }
        while (p1 <= mid) {
            help[index++] = arr[p1++];
        }
        while (p2 <= right) {
            help[index++] = arr[p2++];
        }

        // 拷贝回原数组
        for (int i = 0; i < help.length; i++) {
            arr[left + i] = help[i];
        }
        return ans;
    }


}
